# encoding: UTF-8
import psutil
from PyQt4 import QtCore, QtGui
from cons import *
from manage.uiTradeAccontManage import TradeAccountManage
from manage.uiPortfolioMange import PortfolioManage
from uiStrategy import CtaEngineManager
from engine import *



########################################################################
class MainWindow(QtGui.QMainWindow):
    """主窗口"""

    # ----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        super(MainWindow, self).__init__()

        self.widgetDict = {}  # 用来保存子窗口的字典

        self.initUi()


    # ----------------------------------------------------------------------
    def initUi(self):
        """初始化界面"""
        self.setWindowTitle('Dtrader')
        #self.initCentral()
        self.initMenu()
        self.initStatusBar()


    # ----------------------------------------------------------------------
    def initMenu(self):
        """初始化菜单"""


        # 创建菜单
        menubar = self.menuBar()

        exitAction = QtGui.QAction(u'退出', self)
        exitAction.triggered.connect(self.close)
        sysMenu = menubar.addMenu(u'系统')
        sysMenu.addSeparator()
        sysMenu.addAction(exitAction)


        # 管理菜单
        tradeAccountManageAction = QtGui.QAction(u'交易账户管理', self)
        tradeAccountManageAction.triggered.connect(self.manageTradeAccount)

        portfolioManageAction = QtGui.QAction(u'交易组合管理', self)
        portfolioManageAction.triggered.connect(self.managePortfolio)

        manageMenu = menubar.addMenu(u'管理')

        manageMenu.addAction(tradeAccountManageAction)
        manageMenu.addAction(portfolioManageAction)

        #策略菜单

        simpleStrategyAction = QtGui.QAction(u'常用策略', self)
        simpleStrategyAction.triggered.connect(self.openSimpleStategyWin)

        trendStrategyAction = QtGui.QAction(u'趋势策略', self)
        #trendStrategyAction.triggered.connect(self.openTrendStategyWin)

        machineStrategyAction = QtGui.QAction(u'机器学习策略', self)
        # machineStrategyAction.triggered.connect(self.openMachineStategyWin)
        strategyMenu = menubar.addMenu(u'策略')

        strategyMenu.addAction(simpleStrategyAction)
        strategyMenu.addAction(trendStrategyAction)
        strategyMenu.addAction(machineStrategyAction)

        aboutAction = QtGui.QAction(u'关于', self)
        aboutAction.triggered.connect(self.openAbout)
        # 帮助
        helpMenu = menubar.addMenu(u'帮助')
        helpMenu.addAction(aboutAction)

    def manageTradeAccount(self):
        """打开CTA组件"""
        try:
            self.widgetDict['manTradeW'].showMaximized()
        except KeyError:
            self.widgetDict['manTradeW'] = TradeAccountManage(DB_PATH)
            self.widgetDict['manTradeW'].show()

    def managePortfolio(self):
        try:
            self.widgetDict['manPortfolioW'].showMaximized()
        except KeyError:
            self.widgetDict['manPortfolioW'] = PortfolioManage(DB_PATH)
            self.widgetDict['manPortfolioW'].show()


    def openSimpleStategyWin(self):
        try:
            self.widgetDict['SimpleStategyW'].showMaximized()
        except KeyError:
            mainEngine = Engine()
            self.widgetDict['SimpleStategyW'] = CtaEngineManager(mainEngine)
            self.widgetDict['SimpleStategyW'].show()

    # ----------------------------------------------------------------------
    def initStatusBar(self):
        """初始化状态栏"""
        self.statusLabel = QtGui.QLabel()
        self.statusLabel.setAlignment(QtCore.Qt.AlignLeft)

        self.statusBar().addPermanentWidget(self.statusLabel)
        self.statusLabel.setText(self.getCpuMemory())

        self.sbCount = 0
        self.sbTrigger = 10  # 10秒刷新一次


    # ----------------------------------------------------------------------
    def updateStatusBar(self, event):
        """在状态栏更新CPU和内存信息"""
        self.sbCount += 1

        if self.sbCount == self.sbTrigger:
            self.sbCount = 0
            self.statusLabel.setText(self.getCpuMemory())

    # ----------------------------------------------------------------------
    def getCpuMemory(self):
        """获取CPU和内存状态信息"""
        cpuPercent = psutil.cpu_percent()
        memoryPercent = psutil.virtual_memory().percent
        return u'CPU使用率：%d%%   内存使用率：%d%%' % (cpuPercent, memoryPercent)

        # ----------------------------------------------------------------------


    # ----------------------------------------------------------------------
    def openAbout(self):
        """打开关于"""
        try:
            self.widgetDict['aboutW'].show()
        except KeyError:
            self.widgetDict['aboutW'] = AboutWidget(self)
            self.widgetDict['aboutW'].show()

    # ----------------------------------------------------------------------


class AboutWidget(QtGui.QDialog):
    """显示关于信息"""

    # ----------------------------------------------------------------------
    def __init__(self, parent=None):
        """Constructor"""
        super(AboutWidget, self).__init__(parent)

        self.initUi()

    # ----------------------------------------------------------------------
    def initUi(self):
        """"""
        self.setWindowTitle(u'关于Dtrader')

        text = u"""
            Dtrader是一个简单客户端交易程序

            License：MIT

            """

        label = QtGui.QLabel()
        label.setText(text)
        label.setMinimumWidth(500)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(label)

        self.setLayout(vbox)
